import 'package:flutter/material.dart';
import 'package:adjg_flutter/ad_jg_ad.dart';

import 'key.dart';

class InterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _InterState();
}

class _InterState extends State<InterPage> {
  ADJgIntertitialAd? _interAd;

  @override
  Widget build(BuildContext context) {
    showInterAd();
    return Scaffold(
      appBar: AppBar(
        title: Text("Intertitial"),
      ),
      body: Center(),
    );
  }

  // 插屏
  // 显示插屏广告请保证当时app内没有其他地方显示插屏广告，否则会有冲突
  void showInterAd() {
    if (_interAd != null) {
      return;
    }
    _interAd = ADJgIntertitialAd(posId: KeyManager.interPosid());
    // 加载插屏广告失败
    _interAd!.onFailed = (AdErrorInfo adErrorInfo) {
      print("插屏广告加载失败 errorCode : " +
          adErrorInfo.errorCode.toString() +
          " errorDescription : " +
          adErrorInfo.errorDescription);
      releaseInterAd();
    };
    // 插屏广告曝光回调
    _interAd!.onExposed = (AdInfo adInfo) {
      print("插屏广告曝光了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 插屏广告加载成功回调
    _interAd!.onSucced = (AdInfo adInfo) {
      print("插屏广告成功了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
      playInterAd();
    };
    // 点击插屏回调
    _interAd!.onClicked = (AdInfo adInfo) {
      print("插屏广告点击了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 插屏广告关闭
    _interAd!.onClosed = (AdInfo adInfo) {
      print("插屏广告关闭 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
      releaseInterAd();
    };
    // 加载插屏广告
    _interAd!.load();
  }

  void releaseInterAd() {
    _interAd?.release();
    _interAd = null;
  }

  void playInterAd() {
    // 展示插屏广告
    _interAd!.show();
  }

  @override
  void dispose() {
    releaseInterAd();
    super.dispose();
  }
}
